package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import entity.Order;
import jakarta.servlet.http.HttpSession;
import service.OrderService;
import service.impl.OrderServiceImpl;

import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;


import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;


@WebServlet("/api/orders/*") // 映射路径
public class OrderServlet extends HttpServlet {
    private final OrderService orderService = new OrderServiceImpl();
    private final ObjectMapper objectMapper = new ObjectMapper(); // 用于JSON转换


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String path = req.getPathInfo(); // 获取子路径（如 /getById）
        Map<String, Object> result = new HashMap<>();

        try {
            if ("/getById".equals(path)) {
                // 根据ID查询
                Long id = Long.parseLong(req.getParameter("id"));
                Order order = orderService.getById(id);
                result.put("success", true);
                result.put("data", order);
            } else if ("/getByUserId".equals(path)) {
                // 根据用户ID查询
                HttpSession session = req.getSession();
                Long userId = (Long) session.getAttribute("userId");
                List<Order> orders = orderService.getByUserId(userId);
                objectMapper.registerModule(new JavaTimeModule()); // 关键步骤
                objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

                // 序列化包含 LocalDateTime 的对象
                String json = objectMapper.writeValueAsString(orders); // 此时不会再报错
                result.put("success", true);
                result.put("data", json);
            } else if ("/getByOrderNumber".equals(path)) {
                // 根据订单号查询
                String orderNumber = req.getParameter("orderNumber");
                Order order = orderService.getByOrderNumber(orderNumber);
                result.put("success", true);
                result.put("data", order);
            } else {
                result.put("success", false);
                result.put("message", "无效的GET请求路径");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        out.write(objectMapper.writeValueAsString(result));
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String path = req.getPathInfo();
        Map<String, Object> result = new HashMap<>();

        try {
            if ("/add".equals(path)) {
                // 新增订单
                Order order = new Order();
                order.setUserId(Long.parseLong(req.getParameter("userId")));
                order.setOrderNumber(req.getParameter("orderNumber"));
                order.setProductName(req.getParameter("productName"));
                order.setProductType(req.getParameter("productType"));
                order.setAmount(Double.parseDouble(req.getParameter("amount")));
                order.setStatus(String.valueOf(Integer.parseInt(req.getParameter("status"))));

                orderService.add(order);
                result.put("success", true);
                result.put("message", "订单新增成功");
                result.put("orderId", order.getId()); // 返回自增ID
            } else if ("/update".equals(path)) {
                // 更新订单
                Order order = new Order();
                order.setId(Long.parseLong(req.getParameter("id")));
                // 可选参数：仅更新不为null的字段
                if (req.getParameter("userId") != null) {
                    order.setUserId(Long.parseLong(req.getParameter("userId")));
                }
                order.setOrderNumber(req.getParameter("orderNumber"));
                order.setProductName(req.getParameter("productName"));
                order.setProductType(req.getParameter("productType"));
                if (req.getParameter("amount") != null) {
                    order.setAmount(Double.parseDouble(req.getParameter("amount")));
                }
                if (req.getParameter("status") != null) {
                    order.setStatus(String.valueOf(Integer.parseInt(req.getParameter("status"))));
                }

                int rows = orderService.update(order);
                result.put("success", rows > 0);
                result.put("message", rows > 0 ? "更新成功" : "更新失败");
            } else if ("/delete".equals(path)) {
                // 删除订单
                Long id = Long.parseLong(req.getParameter("id"));
                int rows = orderService.delete(id);
                result.put("success", rows > 0);
                result.put("message", rows > 0 ? "删除成功" : "删除失败");
            } else {
                result.put("success", false);
                result.put("message", "无效的POST请求路径");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }

        out.write(objectMapper.writeValueAsString(result));
    }
}